package com.web.task;

import com.web.dao.CycleRegisterMapper;
import com.web.entity.CycleRegister;
import com.web.entity.Member;
import com.web.manager.cyclecomm.api.impl.EasemobIMUsers;
import io.swagger.client.model.NewPassword;
import io.swagger.client.model.RegisterUsers;
import io.swagger.client.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 *
 * @author FDjavaone
 * @date 2017/11/27
 */
@Component
@Configurable
@EnableScheduling
@Slf4j
public class CycleCommRegister {

    @Autowired
    private CycleRegisterMapper cycleRegisterMapper;
    private EasemobIMUsers easemobIMUsers = new EasemobIMUsers();


    /**@Scheduled(cron = "*//*10 * * * * ?")*/
    public void CycleCommRegister() throws Exception {

        Date date = new Date();
        List<Member> members = cycleRegisterMapper.selectUnRegister();
        log.info("未注册环信的用户数=====" + members.size());
        for (Member m : members) {
            RegisterUsers users = new RegisterUsers();
            User user = new User().username(m.getPhone()).password(m.getPassword());
            users.add(user);
            Object result = easemobIMUsers.createNewIMUserSingle(users);
            if (result != null) {
                //成功注册
                CycleRegister cycleRegister = new CycleRegister();
                cycleRegister.setmId(m.getId());
                cycleRegister.setCreateTime(date);
                cycleRegister.setModifyTime(date);
                cycleRegister.setPhone(m.getPhone());
                cycleRegister.setPassword(m.getPassword());
                cycleRegisterMapper.insertSelective(cycleRegister);
            }
        }

        List<Member> members1 = cycleRegisterMapper.selectNeedChangePassword();
        log.info("环信密码需要更新的用户数=====" + members1.size());
        for (Member m : members1) {
            String userName = m.getPhone();
            NewPassword psd = new NewPassword().newpassword(m.getPassword());
            Object result = easemobIMUsers.modifyIMUserPasswordWithAdminToken(userName, psd);
            if (result != null) {
                //密码修改成功
                CycleRegister old = cycleRegisterMapper.selectByMid(m.getId());
                CycleRegister n = new CycleRegister();
                n.setId(old.getId());
                n.setPassword(m.getPassword());
                n.setModifyTime(date);
                cycleRegisterMapper.updateByPrimaryKeySelective(n);
            }

        }


    }


}
